package com.walter.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.walter.exception.LogicException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ：ch
 * @date ：Created in 2018/8/9
 * @description： 封装Hibernate validator 工具类
 * @modified By：
 * @version: 1.0
 */
public class ValidationUtils {
    private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

    public static void validateProperty(Object obj,String propertyName){
        Set<ConstraintViolation<Object>> set = validator.validateProperty(obj,propertyName);
        if( CollectionUtil.isNotEmpty(set) ){
            Map<String,String> errorMsg = new HashMap<>();
            for(ConstraintViolation<Object> cv : set){ //set size固定为1
                errorMsg.put(RandomUtil.randomUUID(), cv.getMessage());
            }
            Set<String> keys = errorMsg.keySet();
            String msg = "";
            for (String key : keys){
                msg += errorMsg.get(key);
            }
            throw new LogicException(msg);
        }
    }

    public static  void validateEntity(Object obj,Class<?> ... groups){
        Set<ConstraintViolation<Object>> set = validator.validate(obj,groups);
        if( CollectionUtil.isNotEmpty(set) ){
            Map<String,String> errorMsg = new HashMap<>();
            for(ConstraintViolation<Object> cv : set){ //set size至少为1，不超过需要校验的obj属性的个数
                errorMsg.put(RandomUtil.randomUUID(), cv.getMessage());
            }
            throw new LogicException(String.join(",",errorMsg.values()));
        }
    }

}
